//
//  UploadTask.m
//  Scanner
//
//  Created by apple on 15-5-17.
//  Copyright (c) 2015年 米明. All rights reserved.
//

#import "UploadTask.h"
#import "UIImage+Fix.h"
#import "PhotosUploadManager.h"


@implementation UploadTask
{
    UIImage * _photo;
    NSString * _photoPath;
    Goods * _goods;
  
}
-(instancetype)initWithPhotoPath:(NSString *)photoPath goods:(Goods *)goods{
    self=[super init];
    if (self) {
        _photoPath=photoPath;
        self.photoPath=_photoPath;
        _goods=goods;
        [self readyTask];
        
    }
    return self;
}

-(instancetype)initWithPhoto:(UIImage *)photo goods:(Goods *)goods{
    self=[super init];
    if (self) {
        self.photo=photo;
        _photo=photo;
        _goods=goods;
        [self readyTask];
        
    }
    return self;
}


-(void)readyTask{
    
    _isDid=NO;
    _isUploading=NO;
    _succeed=NO;
    
    UIImage * image;
    NSString * type;
    
    if(self.photoPath){
        image=[UIImage imageWithContentsOfFile:self.photoPath];
    }
    else if (self.photo) {
        image=self.photo;
    }

    type=@"jpg";
    
    NSDictionary *parameters =[NSDictionary dictionaryWithObjectsAndKeys:self.goods.Id,@"id", nil];

    // 1. Create `AFHTTPRequestSerializer` which will create your request.
    AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    
    // 2. Create an `NSMutableURLRequest`.
    NSMutableURLRequest *request =
    [serializer multipartFormRequestWithMethod:@"POST" URLString:UPLOAD_PHOTO_URL
                                    parameters:parameters
                     constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
                             [formData appendPartWithFileURL:[NSURL fileURLWithPath:self.photoPath isDirectory:YES] name:@"file" fileName:[[self.photoPath componentsSeparatedByString:@"/"] lastObject] mimeType:[NSString stringWithFormat:@"image/%@",type] error:nil];
                     }];
    
    // 3. Create and use `AFHTTPRequestOperationManager` to create an `AFHTTPRequestOperation` from the `NSMutableURLRequest` that we just created.
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"text/html",@"text/plain",nil];
    
    __weak UploadTask *WEAKSELF=self;
   
    self.operation =
    [manager HTTPRequestOperationWithRequest:request
                                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                         _succeed=YES;
                                         NSLog(@"上传成功");
                                         [[CoreDataManager shareManager]deleteTaskByPhotoPath:self.photoPath];
                                         if ([WEAKSELF.delegate respondsToSelector:@selector(uploadTask:succeed:)]) {
                                             [WEAKSELF.delegate uploadTask:WEAKSELF succeed:YES];
                                             
                                         }
                                    
                                     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                         NSLog(@"Failure %@ %@", operation.responseString,error.description);
                                         _succeed=NO;
                                         NSLog(@"上传失败");
                                         if ([WEAKSELF.delegate respondsToSelector:@selector(uploadTask:error:)]) {
                                             [WEAKSELF.delegate uploadTask:WEAKSELF error:error];
                                         }
                                     }];
    
    // 4. Set the progress block of the operation.
    
    [self.operation setUploadProgressBlock:^(NSUInteger __unused bytesWritten,
                                        long long totalBytesWritten,
                                        long long totalBytesExpectedToWrite) {
        NSLog(@"Wrote %lld/%lld", totalBytesWritten, totalBytesExpectedToWrite);
       
        if ([WEAKSELF.delegate respondsToSelector:@selector(uploadTask:totalBytesWritten:totalBytesExpectedToWrite:)]) {
            [WEAKSELF.delegate uploadTask:WEAKSELF totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
        }
        
    }];
    
   
}

-(void)startTask{
    [self.operation start];
    _isUploading=YES;
    _isDid=YES;
}
-(void)pause{
    [self.operation pause];
}
-(void)resume{
    [self.operation resume];
}
-(void)stop{
    
    self.operation = nil;
}
@end
